import hashlib
import smtplib
import random
import logging
from email.mime.text import MIMEText
from email.header import Header
import bcrypt

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


def send_netease_verification(receiver_email):
    # 网易邮箱配置
    sender_email = "18381823149@163.com"
    auth_code = "PUgtsWWvzpE6HB2N"
    smtp_server = "smtp.163.com"
    smtp_port = 465

    # 生成验证码
    verification_code = ''.join(str(random.randint(0, 9)) for _ in range(6))

    # 邮件内容
    subject = "账号验证验证码"
    content = f"你的验证码是：{verification_code}，5分钟内有效。"

    # 构造邮件（关键修复：只设置一次From字段）
    msg = MIMEText(content, 'plain', 'utf-8')

    # 只保留这一行设置From字段，删除重复项
    msg['From'] = Header(sender_email, 'utf-8')

    msg['To'] = Header(receiver_email, 'utf-8')
    msg['Subject'] = Header(subject, 'utf-8')

    try:
        with smtplib.SMTP_SSL(smtp_server, smtp_port) as server:
            server.set_debuglevel(1)  # 保持调试模式便于排查
            server.login(sender_email, auth_code)
            server.sendmail(
                from_addr=sender_email,
                to_addrs=[receiver_email],
                msg=msg.as_string()
            )
        logging.info(f"验证码已发送至 {receiver_email}，验证码：{verification_code}")
        return verification_code
    except smtplib.SMTPException as e:
        logging.error(f"发送失败：{str(e)}")
        return None

def password_hash(password):
    # 生成盐值，自动处理随机盐
    salt = bcrypt.gensalt()
    # 哈希密码，包含盐值
    hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
    return hashed.decode('utf-8')

def verify_password(password, hashed_password):
    # 验证密码
    return bcrypt.checkpw(
        password.encode('utf-8'),
        hashed_password.encode('utf-8')
    )

if __name__ == "__main__":
    send_netease_verification("tanx79@mail2.sysu.edu.cn")
